package com.ys.controller.api.finance;

import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.entity.finance.TcwWanliPrepaymentRecorded;
import com.ys.entity.finance.TcwWanliReconciliation;
import com.ys.entity.finance.TcwWanliReconciliationItem;
import com.ys.entity.sys.YsCol;
import com.ys.service.finance.TcwWanliPrepaymentRecordedService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.CheckUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 万里汇预付款入账单
 */
@Controller
@RequestMapping("/api/inter/tcwWanliPrepaymentRecorded")
public class ApiInterTcwWanliPrepaymentRecordedController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwWanliPrepaymentRecordedController.class);

    @Autowired
    private CommonApiService<TcwWanliPrepaymentRecorded> commonApiService;

    @Autowired
    private CommonApiService<TcwWanliReconciliation> tcwWanliReconciliationCommonApiService;

    @Autowired
    private CommonApiService<TcwWanliReconciliationItem> tcwWanliReconciliationItemCommonApiService;

    @Autowired
    private TcwWanliPrepaymentRecordedService tcwWanliPrepaymentRecordedService;

    @Autowired
    private YspTaskService yspTaskService;

    @Autowired
    private CheckUtil checkUtil;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwWanliPrepaymentRecorded setSeachSql(TcwWanliPrepaymentRecorded cond,String conditions){

        cond.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人

        .addLeftJoin("YS_ProcInst PI ON PI.Bid = A.Bid ")
                .addField("FORMAT(PI.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS auditingTime")//审核时间

        .addLeftJoin("TCW_DepositPlatform D ON D.Code = A.DepositPlatformCode ")//万里汇账号资金
                .addField("D.PlatformName AS platformName")//收款平台名称
                .addField("D.Code AS depositPlatformCode")//账号编码
                .addField("D.Name AS name")//账号名称
                .addField("D.Mid AS depositPlatformMid")

                .addLeftJoin("TB_CompanyInfo O ON O.Vid = D.CompanyVid ")//公司信息表
                .addField("O.Vname AS vname")//公司名称

                .addLeftJoin("TCW_WanliReconciliation R ON R.Bid = A.ReconciliationBid ")//万里汇预付款对账单
                .addField("R.ReconciliationDayBegin AS reconciliationDayBegin")//对账日期
                .addField("R.ReconciliationDayEnd AS reconciliationDayEnd")//对账日期
                .addField("R.AmountGuijiGbp AS amountGuijiGbp")//GBP归集金额
                .addField("R.AmountGuijiUsd AS amountGuijiUsd")//USD归集金额
                .addField("R.AmountGuijiEur AS amountGuijiEur")//EUR归集金额
                .addField("R.FeeGbp AS feeGbp")//GBP手续费
                .addField("R.FeeUsd AS feeUsd")//USD手续费
                .addField("R.FeeEur AS feeEur")//EUR手续费


                .addLeftJoin("TCW_WanliPrepaymentRecordedItem S ON S.Pbid = A.Bid ")//子表
                .addField("S.RecordedAmount AS recordedAmount")//入账金额（CNY）
                .addLeftJoin("TCW_WanliReconciliationItem I ON I.Id = S.ReconciliationItemId ")//对账表
                .addField("I.RecordAmountGuiji AS recordAmountGuiji")//记录归集金额

                .addLeftJoin("TCW_WanliPrepaymentPooling P ON P.Id = I.WanliPrepaymentPoolingId ")//收款平台账号管理

                .addField("P.FkMid AS fkMid")//付款人MID
                .addField("P.PayerAccountNo AS payerAccountNo")//付款人账号
                .addField("P.PayerName AS fkVyhzhmc")//付款人名称
                .addField("P.fkVyhsx AS fkVyhsx")//付款方账号类型
                .addField("P.Vgsbm AS fkVgsbm")//运营公司编码

                .addLeftJoin("THR_OperateCompanyApply C1 ON C1.Vgsbm = P.Vgsbm ")
                .addField("C1.Vgsjc AS fkVgsjc")//运营公司简称

                .addField("P.SkMid AS skMid")//收款人MID
                .addField("P.BeneficiaryAccountNo AS beneficiaryAccountNo")//收款账号

                .addField("P.BeneficiaryName AS skVyhzhmc")//收款人名称
                .addField("P.skVyhsx AS skVyhsx")//收款方账号类型

                .addField("P.TransactionType AS transactionType")//动账类型
                .addField("P.OriginalTransactionAmount AS originalTransactionAmount")//交易金额
                .addField("P.JyCurrencyCode AS jyCurrencyCode")//交易币种
                .addField("P.ExtTransactionId AS extTransactionId")//商户订单号
                .addField("P.TransactionId AS transactionId")//交易号
                .addField("P.TransactionTime AS transactionTime")//交易创建时间
                .addField("P.TransactionStatus AS transactionStatus")//交易状态
                .addField("P.ReconciliationStatus AS reconciliationStatus")//是否对账


        //排序
        .setOrderby("A.Bid DESC");

        //查询条件
        String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
        if (nameLinked != null){
            cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
        }

        cond = commonApiService.dataAuth(MenuId.TCW_WanliPrepaymentRecorded, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("tcwWanliPrepaymentRecorded:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcwWanliPrepaymentRecorded cond,String conditions
    ){
        try {
            cond = setSeachSql(cond,conditions);
            LayuiTableVoJA setList = commonApiService.searchLay(cond);
            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwWanliPrepaymentRecorded cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond,conditions);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TCW_WanliPrepaymentRecorded)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TcwWanliPrepaymentRecorded> util = new ExportExcelUtils<>(new TcwWanliPrepaymentRecorded());
            String toFilePath = util.exportExcel(listData, listField, "万里汇预付款入账单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 新增
     */
    @RequiresPermissions("tcwWanliPrepaymentRecorded:add")
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcwWanliPrepaymentRecordedService.add(params,MenuId.TCW_WanliPrepaymentRecorded);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 修改
     */
    @RequiresPermissions("tcwWanliPrepaymentRecorded:add")
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tcwWanliPrepaymentRecordedService.update(params,MenuId.TCW_WanliPrepaymentRecorded);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 删除
     */
    @RequiresPermissions("tcwWanliPrepaymentRecorded:add")
    @PostMapping("/toDel")
    @ResponseBody
    public R toDel(Long id){
        try {
            return tcwWanliPrepaymentRecordedService.del(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 删除列表
     */
    @RequiresPermissions("tcwWanliPrepaymentRecorded:add")
    @RequestMapping("/toDelByItem")
    @ResponseBody
    public R toDelByItem(HttpServletRequest request,@RequestParam("list") List<String> idList){
        try {
            //删除
            for (int i = 0; i < idList.size(); i++) {
                tcwWanliPrepaymentRecordedService.toDelByItem(Long.parseLong(idList.get(i)));
            }
            return R.ok();
        } catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    @RequiresPermissions("tcwWanliPrepaymentRecorded:add")
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tcwWanliPrepaymentRecordedService.flowPass(id, ShiroUtils.getUserId());
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 获取计算信息
     */
    @RequestMapping("/toCountInfo")
    @ResponseBody
    public JSONObject toCountInfo(HttpServletRequest request, @RequestParam Map<String, Object> params){
        JSONObject res = new JSONObject();
        try {
            BigDecimal exchangeRateByGbp = BigDecimal.ZERO;
            BigDecimal exchangeRateByUsd = BigDecimal.ZERO;
            BigDecimal exchangeRateByEur = BigDecimal.ZERO;

            if(checkUtil.isNotNullByObject(params.get("exchangeRateByGbp")) ){
                exchangeRateByGbp = new BigDecimal(params.get("exchangeRateByGbp").toString());
            }
            if(checkUtil.isNotNullByObject(params.get("exchangeRateByUsd")) ){
                exchangeRateByUsd = new BigDecimal(params.get("exchangeRateByUsd").toString());
            }
            if(checkUtil.isNotNullByObject(params.get("exchangeRateByEur")) ){
                exchangeRateByEur = new BigDecimal(params.get("exchangeRateByEur").toString());
            }

            //删除列表信息
            //tcwWanliPrepaymentRecordedService.toDelItemByBid(params.get("bid").toString());
            TcwWanliPrepaymentRecorded entity = new TcwWanliPrepaymentRecorded();
            entity.setBid(params.get("bid").toString());

            String reconciliationBid = params.get("reconciliationBid").toString();//对账单bid

            entity.setExchangeRateByGbp(exchangeRateByGbp);
            entity.setExchangeRateByUsd(exchangeRateByUsd);
            entity.setExchangeRateByEur(exchangeRateByEur);

            entity.setReconciliationBid(params.get("reconciliationBid").toString());
            //entity.setDepositPlatformCode(params.get("depositPlatformCode").toString());
            //entity = tcwWanliPrepaymentRecordedService.getExchangeRate(entity);
            entity = tcwWanliPrepaymentRecordedService.countMsg(entity);
            res.put("code",0);

            res.put("exchangeRateByGbp",entity.getExchangeRateByGbp());
            res.put("exchangeRateByUsd",entity.getExchangeRateByUsd());
            res.put("exchangeRateByEur",entity.getExchangeRateByEur());
            res.put("poolingTotal",entity.getPoolingTotal());
            res.put("reconciliationFeeTotal",entity.getReconciliationFeeTotal());
            res.put("countFeeTotal",entity.getCountFeeTotal());
            res.put("recordedTotal",entity.getRecordedTotal());
            res.put("recordedOperations",entity.getRecordedOperations());
            res.put("recordedFinance",entity.getRecordedFinance());
            res.put("amountCny",entity.getAmountCny());

            //获取子表信息
            //List<TcwWanliReconciliationItem> sonList = new TcwWanliReconciliationItem().setPbid(reconciliationBid).queryList();

            List<Map<String, Object>> sonList = new TcwWanliReconciliationItem()
                    //.addField("A.Id AS itemId")//id

                    //.addLeftJoin("TCW_WanliReconciliationItem I ON I.Id = A.ReconciliationItemId ")//对账表
                    .addField("A.RecordAmountGuiji AS recordAmountGuiji")//记录归集金额

                    .addLeftJoin("TCW_WanliPrepaymentPooling P ON P.Id = A.WanliPrepaymentPoolingId ")//收款平台账号管理

                    .addField("P.FkMid AS fkMid")//付款人MID
                    .addField("P.PayerAccountNo AS payerAccountNo")//付款人账号
                    .addField("P.PayerName AS fkVyhzhmc")//付款人名称
                    .addField("P.fkVyhsx AS fkVyhsx")//付款方账号类型
                    .addField("P.Vgsbm AS fkVgsbm")//运营公司编码

                    .addLeftJoin("THR_OperateCompanyApply C1 ON C1.Vgsbm = P.Vgsbm ")
                    .addField("C1.Vgsjc AS fkVgsjc")//运营公司简称

                    .addField("P.SkMid AS skMid")//收款人MID
                    .addField("P.BeneficiaryAccountNo AS beneficiaryAccountNo")//收款账号

                    .addField("P.BeneficiaryName AS skVyhzhmc")//收款人名称
                    .addField("P.skVyhsx AS skVyhsx")//收款方账号类型

                    .addField("P.TransactionType AS transactionType")//动账类型
                    .addField("P.OriginalTransactionAmount AS originalTransactionAmount")//交易金额
                    .addField("P.JyCurrencyCode AS jyCurrencyCode")//交易币种
                    .addField("P.ExtTransactionId AS extTransactionId")//商户订单号
                    .addField("P.TransactionId AS transactionId")//交易号
                    .addField("P.TransactionTime AS transactionTime")//交易创建时间
                    .addField("P.TransactionStatus AS transactionStatus")//交易状态
                    .addField("P.ReconciliationStatus AS reconciliationStatus")//是否对账

                    .setPbid(reconciliationBid)
                    .queryMap();

            //返回子表信息
            res.put("sonList",sonList);

            return res;
        } catch (Exception e) {
            logger.error("获取计算信息出错：",e.getMessage(),e);
            res.put("code",1);
            res.put("msg","系统正在开小差，请联系客服，我们将第一时间为您解决！");
            return res;
        }
    }

    /**
     * 流转驳回
     */
    @RequiresPermissions("tcwWanliPrepaymentRecorded:add")
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){

        try {

            TcwWanliPrepaymentRecorded entity = new TcwWanliPrepaymentRecorded().setId(id).queryFirst();
            return yspTaskService.flowRefuse(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 流转驳回
     */
    @RequiresPermissions("tcwWanliPrepaymentRecorded:add")
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){

        try {
            TcwWanliPrepaymentRecorded entity = new TcwWanliPrepaymentRecorded().setId(id).queryFirst();
            return yspTaskService.flowInit(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }
    


    /**
     * 弹出框 - 万里汇预付款对账单
     */
    @RequestMapping("/searchForModalByWanliReconciliation")
    @ResponseBody
    public LayuiTableVoJA searchForModalByWanliReconciliation(@ModelAttribute TcwWanliReconciliation cond){

        cond.addLeftJoin("TCW_DepositPlatform D ON D.Code = A.DepositPlatformCode ")//收款平台账号管理
                .addField("D.PlatformName AS platformName")//收款平台名称
                .addField("D.Code AS code")//账号编码
                .addField("D.Name AS name")//账号名称
                .addField("D.CompanyVid AS companyVid")

                .addLeftJoin("TB_CompanyInfo O ON O.Vid = D.CompanyVid ")//公司信息表
                .addField("O.Vname AS vname")//公司名称

                .setEffectStock(1);

        //调取未被调取的入账的单号
        cond.where("( SELECT COUNT ( 1 ) AS num FROM TCW_WanliPrepaymentRecorded B WHERE B.ReconciliationBid = A.Bid ) = 0 ");

        return tcwWanliReconciliationCommonApiService.searchLay(cond);
    }

    /**
     * 弹出框 - 万里汇预付款对账单明细
     */
    @RequestMapping("/searchForModalByWanliReconciliationItem")
    @ResponseBody
    public LayuiTableVoJA searchForModalByWanliReconciliationItem(@ModelAttribute TcwWanliReconciliationItem cond){
        cond.addLeftJoin("TCW_WanliPrepaymentPooling P ON P.Id = A.WanliPrepaymentPoolingId ")//收款平台账号管理

                .addField("P.FkMid AS fkMid")//付款人MID
                .addField("P.PayerAccountNo AS payerAccountNo")//付款人账号

                .addField("P.PayerName AS fkVyhzhmc")//付款人名称
                .addField("P.fkVyhsx AS fkVyhsx")//付款方账号类型
                .addField("P.Vgsbm AS fkVgsbm")//运营公司编码

                .addLeftJoin("THR_OperateCompanyApply C1 ON C1.Vgsbm = P.Vgsbm ")
                .addField("C1.Vgsjc AS fkVgsjc")//运营公司简称

                .addField("P.SkMid AS skMid")//收款人MID
                .addField("P.BeneficiaryAccountNo AS beneficiaryAccountNo")//收款账号

                .addField("P.BeneficiaryName AS skVyhzhmc")//收款人名称
                .addField("P.skVyhsx AS skVyhsx")//收款方账号类型

                .addField("P.TransactionType AS transactionType")//动账类型
                .addField("P.OriginalTransactionAmount AS originalTransactionAmount")//交易金额
                .addField("P.JyCurrencyCode AS jyCurrencyCode")//交易币种
                .addField("P.ExtTransactionId AS extTransactionId")//商户订单号
                .addField("P.TransactionId AS transactionId")//交易号
                .addField("P.TransactionTime AS transactionTime")//交易创建时间
                .addField("P.TransactionStatus AS transactionStatus")//交易状态
                .addField("P.ReconciliationStatus AS reconciliationStatus")//是否对账

        .where("A.RecordAmountGuiji !=0 AND P.RecordedStatus !=0 ");//记录归集金额，如为0不被调取

        return tcwWanliReconciliationItemCommonApiService.searchLay(cond);
    }



}